package org.csu.assemblyroom.controller;

import com.alibaba.fastjson.JSON;
import org.csu.assemblyroom.common.CommonResponse;
import org.csu.assemblyroom.entity.User;
import org.csu.assemblyroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户：登录+注册+增删改查
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("add")
    @ResponseBody
    public CommonResponse<User> addUser(@RequestBody String jsonString, HttpServletRequest request){
        User user=JSON.parseObject(jsonString,User.class);
        System.out.println("新增用户为："+user);
        CommonResponse<User> response=userService.addUser(user);
         return response;
    }

    @GetMapping("search/{id}")
    @ResponseBody
    public CommonResponse<User> searchUser(@PathVariable("id") String userid){
             return userService.searchUser(userid);
    }

    @GetMapping("searchAll")
    @ResponseBody
    public CommonResponse<List<User>> searchAllUser(){
      return userService.searchAllUser();
    }

    @DeleteMapping("delete/{id}")
    @ResponseBody
    public CommonResponse<User> deleteUser(@PathVariable("id") String userid){

        try{
            return userService.deleteUser(userid);
        }catch (Exception e){
            return CommonResponse.createForError("删除失败");
        }

    }

    @PutMapping("{id}/update")
    @ResponseBody
    public CommonResponse<User> updateUser(@PathVariable("id") String userid,@RequestBody String jsonString){
        User user=JSON.parseObject(jsonString,User.class);
        CommonResponse<User> response=userService.updateUser(user);
        return response;

    }


}
